package oakclub.service;

import oakclub.global.Container;
import oakclub.model.BlockModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BlockService
{
    private final Logger logger = LoggerFactory.getLogger(BlockService.class);

    public boolean isBlocked(long userId, long targetId) throws Exception
    {
        // get from cache
        MemcachedService memcachedService = (MemcachedService) Container.getComponent(MemcachedService.class);
        String keyId = "" + userId + '.' + targetId;
        Boolean cache = null;
        try
        {
            cache = (Boolean) memcachedService.get(MemcachedService.Key.IS_BLOCKED, keyId);
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }
        if(cache != null)
        {
            boolean isBlocked = cache.booleanValue();
            return isBlocked;
        }

        // get from db
        BlockModel blockModel = (BlockModel) Container.getComponent(BlockModel.class);
        boolean isBlocked = blockModel.isBlocked(userId, targetId);
        cache = Boolean.valueOf(isBlocked);
        try
        {
            memcachedService.set(MemcachedService.Key.IS_BLOCKED, keyId, cache);
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }

        return isBlocked;
    }

    public void blockUser(long userId, long targetId) throws Exception
    {
        BlockModel blockModel = (BlockModel) Container.getComponent(BlockModel.class);
        blockModel.blockUser(userId, targetId);
    }

    public void unblockUser(long userId, long targetId) throws Exception
    {
        BlockModel blockModel = (BlockModel) Container.getComponent(BlockModel.class);
        blockModel.unblockUser(userId, targetId);
    }
}
